<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Validate;
use \app\common\model\User;
use \app\common\model\StudentClassesRelation;
use \app\common\model\Classes;

/**
 * 学生接口
 */
class Students extends Api
{
    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new User();
        $this->studentClassesRelation = new StudentClassesRelation();
        $this->classes = new Classes();
    }

    /**
     * 获取加入班级信息
     * @ApiTitle    (查询班级列表)
     * @ApiParams (name="user_id", type="int", required=true, description="查询用户ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
          'code':'200',
          'msg':'查询成功',
          'time': "",
          'data': $row
        })
     */
    public function getClasses()
    {

        $data = input('get.');
        $userId = $data['user_id'];
        if (!$userId || !Validate::is($userId, 'number')) {
            $this->error('用户ID错误');
        }

        $dis = [
            'id' => $userId,
        ];
        $studentInfo = $this->model->dataInfo($dis, 'id, username, nickname, avatar');
        if (!$studentInfo) {
            $this->success('学生信息不存在', []);
        }

         $dis = [
            'student_id' => $userId,
        ];
        $classRelations = $this->studentClassesRelation->dataList($dis);
        if (!$classRelations) {
            $this->success('未查询到有加入的班级', []);
        }
        $classIds = array_column($classRelations, 'classes_id');

        $dis = [
            'id' =>  ['in', $classIds],
        ];
        $row = $this->classes->dataList($dis);

        // 获取所有教师信息
        $teacherIds = array_unique(array_column($row, 'user_id'));

        $dis = [
            'id' =>  ['in', $teacherIds],
        ];
        $teachers = $this->model->dataMemberId($dis, 'id, username, avatar', 'id');

        $dis = [
            'classes_id' =>  ['in', $classIds],
        ];
        $studentCounts = $this->studentClassesRelation->dataCount($dis, 'classes_id');

        // 组装返回数据
        foreach ($row as &$value) {
            $value['student'] = $studentInfo;
            $value['teacher'] = $teachers[$value['user_id']] ?? null;
            $value['student_count'] = $studentCounts[$value['id']] ?? 0; // 添加班级人数统计
        }
        
        $this->success('查询成功', $row);
    }

}
